'use strict';

const db = uniCloud.database();
const collection = db.collection('food-dishes');

exports.main = async (event, context) => {
  const { operation, dishIds, updateData } = event.data || {};
  
  if (!operation) {
    return {
      code: 400,
      message: '缺少操作类型',
      data: null
    };
  }
  
  if (!dishIds || !Array.isArray(dishIds) || dishIds.length === 0) {
    return {
      code: 400,
      message: '缺少菜品ID列表',
      data: null
    };
  }
  
  try {
    let result;
    let successCount = 0;
    let failCount = 0;
    const failReasons = [];
    
    switch (operation) {
      case 'batch-delete':
        // 批量删除
        for (const dishId of dishIds) {
          try {
            const deleteResult = await collection.doc(dishId).remove();
            if (deleteResult.deleted === 1) {
              successCount++;
            } else {
              failCount++;
              failReasons.push(`菜品 ${dishId} 删除失败`);
            }
          } catch (error) {
            failCount++;
            failReasons.push(`菜品 ${dishId} 删除失败: ${error.message}`);
          }
        }
        break;
        
      case 'batch-update-recommended':
        // 批量更新推荐状态
        if (updateData.is_recommended === undefined) {
          return {
            code: 400,
            message: '缺少推荐状态数据',
            data: null
          };
        }
        
        for (const dishId of dishIds) {
          try {
            const updateResult = await collection.doc(dishId).update({
              is_recommended: updateData.is_recommended,
              update_date: {
                $date: new Date().toISOString()
              }
            });
            if (updateResult.updated === 1) {
              successCount++;
            } else {
              failCount++;
              failReasons.push(`菜品 ${dishId} 更新失败`);
            }
          } catch (error) {
            failCount++;
            failReasons.push(`菜品 ${dishId} 更新失败: ${error.message}`);
          }
        }
        break;
        
      case 'batch-update-spiciness':
        // 批量更新辣度
        if (updateData.spiciness === undefined) {
          return {
            code: 400,
            message: '缺少辣度数据',
            data: null
          };
        }
        
        for (const dishId of dishIds) {
          try {
            const updateResult = await collection.doc(dishId).update({
              spiciness: parseInt(updateData.spiciness),
              update_date: {
                $date: new Date().toISOString()
              }
            });
            if (updateResult.updated === 1) {
              successCount++;
            } else {
              failCount++;
              failReasons.push(`菜品 ${dishId} 更新失败`);
            }
          } catch (error) {
            failCount++;
            failReasons.push(`菜品 ${dishId} 更新失败: ${error.message}`);
          }
        }
        break;
        
      case 'batch-update-category':
        // 批量更新分类
        if (updateData.category_id === undefined) {
          return {
            code: 400,
            message: '缺少分类ID数据',
            data: null
          };
        }
        
        for (const dishId of dishIds) {
          try {
            const updateResult = await collection.doc(dishId).update({
              category_id: updateData.category_id,
              update_date: {
                $date: new Date().toISOString()
              }
            });
            if (updateResult.updated === 1) {
              successCount++;
            } else {
              failCount++;
              failReasons.push(`菜品 ${dishId} 更新失败`);
            }
          } catch (error) {
            failCount++;
            failReasons.push(`菜品 ${dishId} 更新失败: ${error.message}`);
          }
        }
        break;
        
      case 'batch-update-status':
        // 批量更新状态
        if (updateData.status === undefined) {
          return {
            code: 400,
            message: '缺少状态数据',
            data: null
          };
        }
        
        for (const dishId of dishIds) {
          try {
            const updateResult = await collection.doc(dishId).update({
              status: parseInt(updateData.status),
              update_date: {
                $date: new Date().toISOString()
              }
            });
            if (updateResult.updated === 1) {
              successCount++;
            } else {
              failCount++;
              failReasons.push(`菜品 ${dishId} 更新失败`);
            }
          } catch (error) {
            failCount++;
            failReasons.push(`菜品 ${dishId} 更新失败: ${error.message}`);
          }
        }
        break;
        
      default:
        return {
          code: 400,
          message: '不支持的操作类型',
          data: null
        };
    }
    
    return {
      code: 200,
      message: '批量操作完成',
      data: {
        successCount,
        failCount,
        failReasons,
        total: dishIds.length
      }
    };
  } catch (error) {
    return {
      code: 500,
      message: '批量操作失败',
      data: null
    };
  }
};